package com.na.report.filter;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.na.report.Action;
import com.na.report.Application;

public class GlobalFilter implements Filter {

	static final Logger log = LoggerFactory.getLogger(GlobalFilter.class);
	
	Map<String, Action> actions = Collections.emptyMap();
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		String sec = req.getParameter("sec");
		if (!Application.getConfig().sec.equals(sec)) {
			res.getWriter().println("denied");
			return;
		}
		Action action = actions.get(((HttpServletRequest) req).getServletPath());
		if (action != null) {
			try {
				action.execute((HttpServletRequest) req, (HttpServletResponse) res);
			} catch (Exception e) {
				log.error("[ACTION EXECUTE]ERROR", e);
			}
			return;
		}
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		actions = new HashMap<String, Action>(Application.getConfig().actions);
		Application.getConfig().actions = null; // gc
		log.info("[GLOBAL FILTER INIT]OK");
	}

}
